<?php

include "dataConfig.php"; 

if($_SERVER["REQUEST_METHOD"] != "POST"){
    print_r(json_encode(array("msg" => "不支持get请求", "status" => 0)));
    return;
}

$UID = $_POST["uid"];
$GID = $_POST["g_id"]; 
$TITLE = $_POST["title"];  
$NEWPRICE = $_POST["newprice"]; 
$PRICE = $_POST["price"]; 
$IMG = $_POST["img"]; 
$NUM = $_POST["num"]; 
$TOTAL = $NEWPRICE * $NUM; 

$sqlQuery = "SELECT * FROM cart WHERE uid= ?";

$stmt = $conn->prepare($sqlQuery);
$stmt->bind_param("i", $UID);
$stmt->execute();
$queryResult = $stmt->get_result();

$flag = true;  
while($row = $queryResult->fetch_assoc()){
    if($row["g_id"] == $GID){
        $flag = false;//找到了,就做修改 update
        break;
    }
} 
if($flag == true){ 
    $sqlInert = "INSERT INTO cart (`uid`,`g_id`,`title`,`newprice`,`img`,`num`,`total`,`price`) VALUES (?,?,?,?,?,?,?,?)";
 
    $stmtI = $conn->prepare($sqlInert);
    $stmtI->bind_param("iisssiss", $UID, $GID, $TITLE, $NEWPRICE, $IMG, $NUM,$TOTAL,$PRICE);
    $stmtI->execute();

    if($stmtI->affected_rows >= 1){
        print_r(json_encode(array("msg" => "加入购车成功i", "status" => 1)));
    } else {
        print_r(json_encode(array("msg" => "加入购车失败i", "status" => -1)));
    }

    $stmtI->close();


} else {

    $sqlUpdate = "UPDATE cart SET  num=num+? ,total=num*newprice WHERE uid=?  and g_id=?";

    $stmtU = $conn->prepare($sqlUpdate);
    $stmtU->bind_param("iii", $NUM,$UID,$GID);
    $stmtU->execute();

    if($stmtU->affected_rows >= 1){
        print_r(json_encode(array("msg" => "加入购车成功u", "status" => 1)));
    } else {
        print_r(json_encode(array("msg" => "加入购车失败u", "status" => -1)));
    }
    $stmtU->close();
}

$conn->close(); 